package com.lk.service;

import com.lk.mapper.MenuMapper;
import com.lk.mapper.UserMapper;
import com.lk.model.Menu;
import com.lk.model.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author : lk
 * @date 2021/11/20 14:30
 **/
@Service
public class UserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User oneUser = userMapper.getOneUser(username);
        if (Objects.isNull(oneUser)) {
            throw new UsernameNotFoundException("用户名找不到");
        }
        List<Menu> menuList = menuMapper.menuList(oneUser.getUserId());
        Collection<GrantedAuthority> grantedAuthorities=new HashSet<>();
        menuList.forEach(str->{
            SimpleGrantedAuthority e = new SimpleGrantedAuthority(str.getUrl());
            grantedAuthorities.add(e);
        });
        return new org.springframework.security.core.userdetails.User(oneUser.getUsername(), oneUser.getPassword(),grantedAuthorities);
    }


}
